using System;
using GalaSoft.MvvmLight;
using System.Collections.ObjectModel;
using Locator.Silverlight.Client.Models.ViewModels.Elements;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using Locator.Silverlight.Client.Models.InventoryServiceReference;
using System.Collections.Generic;
using System.Linq;

namespace Locator.Silverlight.Client.Models.ViewModels.Screens
{
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// The <see cref="Products" /> property's name.
        /// </summary>
        public const string ProductsPropertyName = "Products";
        private readonly IInventoryModel inventoryModel;
        private bool productsLoaded;
        private bool storesLoaded;
        private readonly object isBusyLock = new object();
        private bool finding;

        /// <summary>
        /// The <see cref="CurrentStore" /> property's name.
        /// </summary>
        public const string CurrentStorePropertyName = "CurrentStore";

        private StoreViewModel currentStore;

        /// <summary>
        /// Gets the CurrentStore property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public StoreViewModel CurrentStore
        {
            get
            {
                return currentStore;
            }

            set
            {
                if (currentStore != value)
                {
                    currentStore = value;

                    // Update bindings, no broadcast
                    RaisePropertyChanged(CurrentStorePropertyName);
                }
            }
        }

        /// <summary>
        /// The <see cref="Stores" /> property's name.
        /// </summary>
        public const string StoresPropertyName = "Stores";

        private ObservableCollection<StoreViewModel> stores;

        /// <summary>
        /// Gets the Stores property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<StoreViewModel> Stores
        {
            get { return stores; }

            set
            {
                if (stores == value)
                {

                }
                else
                {
                    stores = value;

                    // Update bindings, no broadcast
                    RaisePropertyChanged(StoresPropertyName);
                }
            }
        }

        /// <summary>
        /// The <see cref="CurrentProduct" /> property's name.
        /// </summary>
        public const string CurrentProductPropertyName = "CurrentProduct";

        private ProductViewModel currentProduct;

        /// <summary>
        /// Gets the CurrentProduct property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ProductViewModel CurrentProduct
        {
            get { return this.currentProduct; }

            set
            {
                if (this.currentProduct != value)
                {
                    this.currentProduct = value;

                    // Update bindings, no broadcast
                    RaisePropertyChanged(CurrentProductPropertyName);
                }
            }
        }

        private ObservableCollection<ProductViewModel> products;

        /// <summary>
        /// Gets the Products property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<ProductViewModel> Products
        {
            get { return products; }

            set
            {
                if (products == value)
                {
                }
                else
                {
                    products = value;
                    // Update bindings, no broadcast
                    RaisePropertyChanged(ProductsPropertyName);
                }
            }
        }

        /// <summary>
        /// The <see cref="StoresWithInventories" /> property's name.
        /// </summary>
        public const string StoresWithInventoriesPropertyName = "StoresWithInventories";

        private ObservableCollection<StoreWithInventoryViewModel> storesWithInventories;

        /// <summary>
        /// Gets the StoresWithInventories property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public ObservableCollection<StoreWithInventoryViewModel> StoresWithInventories
        {
            get { return storesWithInventories; }

            set
            {
                if (storesWithInventories == value)
                {
                    return;
                }

                storesWithInventories = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(StoresWithInventoriesPropertyName);
            }
        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
            : this(new InventoryModel())
        {

        }

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        /// <param name="inventoryModel"></param>
        public MainViewModel(IInventoryModel inventoryModel)
        {
            this.inventoryModel = inventoryModel;
            this.FindProductsCommand = new RelayCommand(() => this.FindProducts(), () => !this.IsBusy);
            if (IsInDesignMode)
            {
#if DEBUG
                this.Products = new ObservableCollection<ProductViewModel>() { 
                    new ProductViewModel() { Id = 123, Name = "Domaine De La Seigneurie Des Tourelles Saumur 2008 750 mL bottle" },
                    new ProductViewModel() { Id = 124, Name = "Product 124" }
                };

                StoreViewModel newStoreModel1 = new StoreViewModel() { Id = 123 };
                newStoreModel1.SetAddress("Address 123", "City 123");
                StoreViewModel newStoreModel2 = new StoreViewModel() { Id = 124 };
                newStoreModel2.SetAddress("Address 124", "City 124");
                this.Stores = new ObservableCollection<StoreViewModel>() { 
                    newStoreModel1,
                    newStoreModel2
                };

                this.CurrentStore = this.Stores[0];

                this.CurrentProduct = this.Products[0];

                ObservableCollection<InventoryInfo> invInfo = new ObservableCollection<InventoryInfo>();
                invInfo.Add(new InventoryInfo() { NumberInStock = 33, Product = new ProductListItem() { Id = 33, Name = "Domaine De La Seigneurie Des Tourelles Saumur 2008 750 mL bottle" } });
                invInfo.Add(new InventoryInfo() { NumberInStock = 5600, Product = new ProductListItem() { Id = 56, Name = "Canadian" } });

                List<StoreWithInventory> sWithInv = new List<StoreWithInventory>();
                sWithInv.Add(new StoreWithInventory()
                {
                    Inventory = invInfo,
                    Store = new InvStore()
                    {
                        City = "City 123",
                        Address = "Address 123",
                        StoreNumber = 123,
                        Latitude = 43.474249M,
                        Longitude = -79.732728M
                    }
                });
                sWithInv.Add(new StoreWithInventory()
                {
                    Inventory = invInfo,
                    Store = new InvStore()
                    {
                        City = "City 124",
                        Address = "Address 124",
                        StoreNumber = 124,
                        Latitude = 43.574249M,
                        Longitude = -79.632728M
                    }
                });

                this.StoresWithInventories = new ObservableCollection<StoreWithInventoryViewModel>();
                foreach (StoreWithInventory storeWithInventory in sWithInv)
                {
                    this.StoresWithInventories.Add(new StoreWithInventoryViewModel(storeWithInventory));
                }
#endif
            }
            else
            {
                this.Refresh();
            }
        }

        public RelayCommand FindProductsCommand { get; private set; }


        /// <summary>
        /// The <see cref="IsBusy" /> property's name.
        /// </summary>
        public const string IsBusyPropertyName = "IsBusy";

        private bool isBusy = true;

        /// <summary>
        /// Gets the IsBusy property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool IsBusy
        {
            get { return isBusy; }

            set
            {
                if (isBusy == value)
                {
                    return;
                }

                isBusy = value;

                // Update bindings, no broadcast
                RaisePropertyChanged(IsBusyPropertyName);
            }
        }

        private void Refresh()
        {
            inventoryModel.GetProductsForUserAsync((products, error) =>
            {
                if (error != null)
                {
                    // Display error, normally this would be done through a property
                    MessageBox.Show(error.Message);
                    return;
                }

                List<ProductViewModel> productsForUI = products.ToList();
                productsForUI.Insert(0, new ProductViewModel() { Id = ProductConstants.UsersProductsId, Name = "Your products" });
                this.Products = new ObservableCollection<ProductViewModel>(productsForUI);
                this.CurrentProduct = this.Products[0];
                lock (this.isBusyLock)
                {
                    this.productsLoaded = true;
                    if (this.storesLoaded)
                    {
                        this.IsBusy = false;
                        this.FindProductsCommand.RaiseCanExecuteChanged();
                    }
                }
            });

            inventoryModel.GetStoresForUserAsync((stores, error) =>
            {
                if (error != null)
                {
                    // Display error, normally this would be done through a property
                    MessageBox.Show(error.Message);
                    return;
                }

                List<StoreViewModel> storesForUI = stores.ToList();
                StoreViewModel newStoreViewModel1 = new StoreViewModel() { Id = StoreConstants.UsersStoresId };
                newStoreViewModel1.SetAddress("Your stores", null);
                StoreViewModel newStoreViewModel2 = new StoreViewModel() { Id = StoreConstants.AllStoresId };
                newStoreViewModel2.SetAddress("All stores", null);
                storesForUI.Insert(0, newStoreViewModel1);
                storesForUI.Insert(1, newStoreViewModel2);
                this.Stores = new ObservableCollection<StoreViewModel>(storesForUI);
                this.CurrentStore = this.Stores[0];
                lock (this.isBusyLock)
                {
                    this.storesLoaded = true;
                    if (this.productsLoaded)
                    {
                        this.IsBusy = false;
                        this.FindProductsCommand.RaiseCanExecuteChanged();
                    }
                }
            });
        }

        ////public override void Cleanup()
        ////{
        ////    // Clean up if needed

        ////    base.Cleanup();
        ////}

        private void FindProducts()
        {
            if (this.IsBusy)
            {
                return;
            }

            this.IsBusy = true;
            this.FindProductsCommand.RaiseCanExecuteChanged();

            InventoryRequestHelper request = new InventoryRequestHelper(this.CurrentStore, this.CurrentProduct);

            this.inventoryModel.GetInventoriesAsync(request, (stores, error) =>
            {
                if (error != null)
                    // Display error, normally this would be done through a property
                    MessageBox.Show(error.Message);
                else
                    this.StoresWithInventories = new ObservableCollection<StoreWithInventoryViewModel>(stores);

                this.IsBusy = false;
                this.FindProductsCommand.RaiseCanExecuteChanged();
            });

        }

        public bool CanFind
        {
            get
            {
                lock (this.isBusyLock)
                {
                    return this.productsLoaded && this.storesLoaded;
                }
            }
        }
    }
}
